<template>
  <zero-dialog :showDialog.sync="dialog.open" :width="dialog.width" :title="dialog.title"
               :fullscreen.sync="dialog.fullscreen" :id="dialog.id" :submit="submitForm">
    <div slot="body">
      <vxe-form :ref="form.ref" :data="form.info" :rules="form.rules" title-align="right" title-width="100">
        <vxe-form-item title="分组" field="datasourceId" :item-render="{}" span="24">
          <template #default="{ data }">
            <vxe-select v-model="data.groupCode" placeholder="请选择分组" clearable filterable>
              <vxe-option v-for="groupCode in groupCodeList" :key="groupCode" :label="groupCode"
                          :value="groupCode"></vxe-option>
            </vxe-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="代码生成方式" field="genWay" :item-render="{}" span="24">
          <template #default="{ data }">
            <vxe-radio v-model="data.genWay" v-for="dict in dict.type.gen_way" :key="dict.value" :label="dict.value">{{
                dict.label
              }}
            </vxe-radio>
          </template>
        </vxe-form-item>
      </vxe-form>
    </div>
  </zero-dialog>
</template>


<script>
import addUpdate from '@/mixins/add-update.js';

export default {
  name: 'genCode',
  mixins: [addUpdate],
  dicts: ['gen_way'],
  data() {
    return {
      groupCodeList: [],//数据源
      axios: this.$axiosGen, // 请求的微服务
      dialog: {
        width: '800px', //定义宽度
      },
      form: {//表单数据
        rules: { //表单验证
          name: [{required: true, message: "名称不能为空", trigger: "blur"}],
          groupCode: [{required: true, message: "分组编码不能为空", trigger: "blur"}],
          occupationPath: [{required: true, message: "占位路径不能为空", trigger: "blur"}]
        }
      }
    }
  },
  created() {

    let config = {
      url: "/templateInfo/groupSelect",
      method: 'post'
    }
    this.$axiosGen(config).then(res => {
      this.groupCodeList = res.data
    }).finally(() => {
    });
  },
  methods: {
    submitForm() {
      this.$refs[this.form.ref].validate((valid) => {
        if (!valid) {
          let data = []
          //弹框的loading
          let loading = this.$loading({target: `#${this.dialog.id} >div >.el-dialog`});
          let config = {
            url: "/tableInfo/genCode",
            method: 'post',
            data: {tableInfoIdList: [this.form.info.id], groupCode: this.form.info.groupCode, genWay: this.form.info.genWay}
          }
          if (this.form.info.genWay === '0') {
            config.responseType = 'blob'
          }
          this.axios(config).then(res => {
            if (this.form.info.genWay === '0') {
              // 检查响应是否为Blob对象（正常的文件下载）
              if (res instanceof Blob) {
                const blob = new Blob([res], {
                  type: 'application/zip;charset=UTF-8'
                })
                const downloadElement = document.createElement('a')
                const href = window.URL.createObjectURL(blob) // 创建下载的链接
                downloadElement.href = href
                downloadElement.download = 'generator.zip' // 下载后文件名
                document.body.appendChild(downloadElement)
                downloadElement.click() // 点击下载
                document.body.removeChild(downloadElement) // 下载完成移除元素
                window.URL.revokeObjectURL(href) // 释放掉blob对象
                this.$modal.msgSuccess("操作成功");
                this.dialog.open = false;
              } else {
                // 如果不是Blob，说明是JSON响应（可能是成功的JSON响应）
                this.$modal.msgSuccess("操作成功");
                this.dialog.open = false;
              }
            } else {
              this.$modal.msgSuccess("操作成功");
              this.dialog.open = false;
            }
          }).catch((error) => {
            // 错误处理已经在响应拦截器中统一处理了
            console.error('操作失败:', error);
          }).finally(() => {
            loading.close()
          });
        }
      })
    }
  }
}
</script>
